//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 梁智 on 15/12/2.
//  Copyright © 2015年 lzfree. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self](emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    
    /// 照片选择控制器
    private lazy var picturePickerController = PicturePickerController()
    
    // MARK: - 监听方法
    @objc private func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendStatus() {
        let text = textView.emoticonText
        
        SVProgressHUD.show()
        NetworkTools.sharedTools.sendStatus(text, image: picturePickerController.pictures.last) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("您的网络不给力啊")
                return
            }
            SVProgressHUD.showInfoWithStatus("发布成功")
            delay(0.25) {
                
                self.close()
            }
        }
    }
    
    /// 选择照片
    @objc private func selectPicture() {
        // 退掉键盘
        textView.resignFirstResponder()
        
        // 0. 判断如果已经更新了约束，不再执行后续代码
        if picturePickerController.view.frame.height > 0 {
            return
        }
        
        // 1. 修改照片选择控制器视图的约束
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        // 2. 修改文本视图的约束 - 重建约束 - 会将之前`textView`的所有的约束删除
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        // 3. 动画更新约束
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    /// 选择表情
    @objc private func selectEmoticon() {
        // 如果使用的是系统键盘 textView.inputView = nil
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        textView.becomeFirstResponder()
    }
    
    /// 键盘变化通知
    @objc private func keyboardChanged(noti: NSNotification) {
        //print(noti)
        
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let curve = (noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -view.bounds.height + rect.origin.y
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            // 设置动画曲线
            /**
            曲线值 = 7
            － 如果之前的动画没有完成，有启动了其他的动画，让动画的图层直接运动到后续动画的目标位置
            － 一旦设置了 `7`，动画时长无效，动画时长统一变成 0.5s
            */
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
        // 调试动画时长 － keyPath 将动画添加到图层
        let anim = toolbar.layer.animationForKey("position")
        print("动画时长 \(anim?.duration)")
    }
    
    override func loadView() {
        super.loadView()
        
        view = UIView()
        
        setupUI()
    }
    
    // MARK: - 键盘处理
    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 激活键盘 - 如果已经存在照片控制器视图，不再激活键盘
        if picturePickerController.view.frame.height == 0 {
            textView.becomeFirstResponder()
        }
    }

    // MARK: - 懒加载控件
    private lazy var toolbar: UIToolbar = UIToolbar()
    /// 文本视图
    private lazy var textView: UITextView = {
        let tv = UITextView()
        
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        // 始终允许垂直滚动
        tv.alwaysBounceVertical = true
        // 拖动关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.delegate = self
        
        return tv
    }()
    /// 占位标签
    private lazy var placeHolderLabel = UILabel(title: "分享新鲜事...",
        fontSize: 18, color:
        UIColor.lightGrayColor())
}

// MARK: - 
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = true
    }
}

// MARK: - 设置界面
extension ComposeViewController {
    
    private func setupUI() {
        // 取消自动调整滚动视图间距
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNavigationBar()
        prepareToolbar()
        prepareTextView()
        preparePicturePicker()
    }
    
    /// 准备照片选择控制器
    private func preparePicturePicker() {
        
        // 0. 添加子控制器
        addChildViewController(picturePickerController)
        
        // 1. 添加视图
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
       
        // 2. 自动布局
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
        }
    }
    
    /// 准备导航栏
    private func prepareNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendStatus")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题栏视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        let titleLabel = UILabel(title: "发布微博", fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "", fontSize: 13, color: UIColor.lightGrayColor())
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
        navigationItem.titleView = titleView
    }
    
    /// 准备工具栏
    func prepareToolbar() {
        view.addSubview(toolbar)
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        // 添加工具栏按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
                
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"]))
    
        
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))

        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    /// 准备文本视图
    private func prepareTextView() {
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        
        //textView.text = "分享新鲜事..."
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
}